<?php
// TODO: dodawanie, edytowanie, usuwanie products
session_start();
class Controller_Admin_Product extends Controller_Admin_Abstract
{	
	public function __construct(Controller_Front $frontController)
	{
		parent::__construct('admin_product', $frontController);
	}
	
	public function indexAction()
	{
		$this->view()->display('admin_products.tpl');
	}
	
	public function newAction()
	{
		$products;
		$buttonName;
		
		if (isset($_GET['id_product'])) {
			$id = $_GET['id_product'];
			$buttonName = 'Edytuj';
			
			$products = ProductsPeer::retrieveByPK($id);
		} else {
			$buttonName = 'Dodaj';
			$products = new Products();
		}
		$this->view()->assign('products', $products);
		$this->view()->assign('editButton', $buttonName);
		$this->view()->assign('producers', ProducersPeer::doSelect(new Criteria()));
		$this->view()->assign('categories', CategoriesPeer::doSelect(new Criteria()));
		$_SESSION['enable']=true;
		$this->view()->display('admin_products_edit.tpl');
	}
	
	public function listAction()
	{
		$products = ProductsPeer::doSelect(new Criteria());
		//var_dump($categories);
		$this->view()->assign('products', $products);
		
		$this->view()->display('admin_products_list.tpl');
	}
	
	public function checkAction()
	{		
		$products;
		
		if (!empty($_POST['id_product'])) {
			$id = $_POST['id_product'];
			
			$products = productsPeer::retrieveByPK($id);
		} else {
			$products = new Products();
		}
		
		if($_SESSION["enable"]==true) {
			$products->setName($_POST['name']);
			$products->setDescription($_POST['description']);
			$products->setIdProducer($_POST['id_producer']);
			$products->setIdCategory($_POST['id_category']);
			$products->save();
			$this->ok('Product saved.');	
			$_SESSION['enable']=false;	
		} else {
			$this->fail('Re-saving it is not possible.');
		}
	}	
	
	public function deleteAction()
	{
		
		if (!isset($_GET['id_product'])) {
			throw new Exception('id not spec');
		}	
		
		$id = $_GET['id_product'];
		try {
			NewsPeer::doDelete($id);
		} catch (Exception $e) {
			$this->view()->assign('fail_info', 'Nie uda�o si� usun�� ' 
				. $e->getMessage());  	
			return $this->view()->display('fail.tpl');		
		}
				
			
	}
	
}